package com.app.micaihu.utils;

import android.text.TextUtils;

import com.android.volley.VolleyError;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.db.NewsDBSqlHelper;
import com.app.micaihu.db.NewsDBUtil;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.listener.HttpListener;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 收藏工具类
 * Created by linkai on 2016/7/27.
 */
public class CollectUtils {

    private static CollectUtils mCollectUtils;

    private CollectUtils() {
    }

    /**
     * 构造单例模式
     *
     * @return
     */
    public static CollectUtils getInstance() {
        if (mCollectUtils == null) {
            mCollectUtils = new CollectUtils();
        }
        return mCollectUtils;
    }


    /**
     * 请求网络收藏新闻
     * 成功 则存储到本地
     *
     * @param newsid
     */
    public boolean saveNews(String newsid) {
        if (TextUtils.isEmpty(newsid)) {
            return false;
        }
        ParamMap parmsMap = new ParamMap();
        if (UserInforManager.getInstance().isLogin()) {
            parmsMap.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
        } else {
            parmsMap.putEncode("uid", "");
        }
        parmsMap.put("ids", newsid);
        HttpUtils.ParmsMapMD5(parmsMap);

        HttpListener<DataBean<NewsEntity>> httpListener = new HttpListener<DataBean<NewsEntity>>() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(DataBean<NewsEntity> response) {
                //如果请求成功 则存储到本地
                if (response.noError()) {
                    String saveTime = "" + System.currentTimeMillis();
                    NewsDBUtil.getInstance().addSaveNews(response.getData(), NewsDBSqlHelper.NEWS_SAVE, saveTime);
                }
            }
        };
        HttpUtils.addPostRequest(URIContant.NEWS_COLLECT_ADD, new TypeToken<DataBean<NewsEntity>>() {
        }.getType(), null, parmsMap, httpListener);
        return true;
    }


    /**
     * 上传本地的收藏数据
     */
    public void uploadLocalSaveNews() {
        String ids = getLocalNewsId();//获取本地的文章id集合字符串
        if (TextUtils.isEmpty(ids)) {
            //本地无数据 不上传
            return;
        }
        if (!UserInforManager.getInstance().isLogin()) {
            //没登陆不上传
            return;
        }
        ParamMap parmsMap = new ParamMap();
        parmsMap.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
        parmsMap.putEncode("ids", ids);
        HttpUtils.ParmsMapMD5(parmsMap);
        HttpUtils.addPostRequest(URIContant.NEWS_COLLECT_ADD, new TypeToken<DataBean<String>>() {
        }.getType(), null, parmsMap, null);
    }

    /**
     * 获取本地存储的新闻id集合
     *
     * @return
     */
    private String getLocalNewsId() {
        String sql = "select * from " + NewsDBSqlHelper.NEWS_SAVE;
        List<String> list = NewsDBUtil.getInstance().getListID(sql);
        if (list != null && list.size() > 0) {
            String ids = "";
            for (int i = 0; i < list.size(); i++) {
                ids += list.get(i) + ",";
            }
            return ids;
        }
        return null;
    }

    /**
     * 获取用户收藏的新闻列表
     *
     * @return
     */
    public List<NewsEntity> getLocalNewsList(int offset, int limit) {
        Object cacheList = NewsDBUtil.getInstance().listCache(null, null, "saveTime desc", NewsDBUtil.getInstance().getCollectionTable(), offset + "," + limit);//offset+","+MaxResult
        if (cacheList != null && !((List) cacheList).isEmpty()) {
            List<Map<String, String>> maplist = (List) cacheList;
            int count = maplist.size();
            List<NewsEntity> list = new ArrayList<NewsEntity>();
            for (int i = 0; i < count; i++) {
                NewsEntity navigate = new NewsEntity();
                navigate.setArticleId(maplist.get(i).get("_id"));
                navigate.setArticleAttr(maplist.get(i).get("articleAttr"));
                navigate.setArticleMark(maplist.get(i).get("articleMark"));
                navigate.setArticleTime(maplist.get(i).get("articleTime"));
                navigate.setArticleTitle(maplist.get(i).get("articleTitle"));
                navigate.setArticleType(maplist.get(i).get("articleType"));
                navigate.setCategoryId(maplist.get(i).get("categoryId"));
                navigate.setCommentNum(maplist.get(i).get("commentNum"));
                navigate.setPicNum(maplist.get(i).get("picNum"));
                navigate.setUiType(maplist.get(i).get("uiType"));
                navigate.setPraiseNum(maplist.get(i).get("praiseNum"));
                String articleThumb = maplist.get(i).get("articleThumb");
                if (!TextUtils.isEmpty(articleThumb)) {
                    //如果有图集字符串则 转成数组
                    String[] picArray = articleThumb.split("~");

                    navigate.setArticleThumb(picArray);
                }

                list.add(navigate);
            }
            if (!list.isEmpty()) {
                return list;
            }
        }
        return null;
    }

    /**
     * 删除稿子数据
     *
     * @param newsid
     * @return
     */
    public boolean deleteSaveNews(String newsid) {
        if (TextUtils.isEmpty(newsid)) {
            return false;
        }
        //进行本地删除
        String sql = "delete from " + NewsDBSqlHelper.NEWS_SAVE
                + " where _id=" + newsid;
        NewsDBUtil.getInstance().changeData(sql);

        //如果用户登录了则请求网络 删除收藏
        if (UserInforManager.getInstance().isLogin()) {
            //HashMap<String,String> parmsMap = new HashMap<String,String>();

            ParamMap parmsMap = new ParamMap();
            parmsMap.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
            parmsMap.putEncode("ids", newsid);

            HttpUtils.ParmsMapMD5(parmsMap);
            HttpUtils.addPostRequest(URIContant.NEWS_COLLECT_DELETE, new TypeToken<DataBean>() {
            }.getType(), null, parmsMap, new HttpListener<DataBean>() {
                @Override
                public void onError(VolleyError error) {
                }

                @Override
                public void onSuccess(DataBean response) {
                }
            });
        }
        return true;
    }

    /**
     * 查询本地是否收藏某条新闻
     *
     * @param newsid
     * @return
     */
    public boolean querySaveId(String newsid) {
        //进行本地删除
        String sql = "select _id from " + NewsDBSqlHelper.NEWS_SAVE
                + " where _id=" + newsid;
        boolean b = NewsDBUtil.getInstance().hasDataBySql(sql);
        return b;
    }


}
